﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevExpress.Web.Mvc;
using ThinhTien.EF4;
using ThinhTien.Models;
using DevExpress.Data;
using DevExpress.Data.Filtering;
using DevExpress.Data.Linq;
using DevExpress.Data.Linq.Helpers;

namespace ThinhTien.Data.Repository
{
    public class CategoryRepository : BaseRepository<CategoryRepository>
    {

        public void AddNew(CategoryViewModel model)
        {
           
            try
            {
                using (var db = new THINHTIENDBEntities())
                {
                    Guid? imageID = null;

                    if (model.Photo != null)
                    {
                        imageID = Guid.NewGuid();

                        db.Images.Add(new Image
                        {
                            ID = imageID.Value,
                            Size = model.Photo.Length,
                            Image1 = model.Photo,
                            Filename = model.Name
                        });
                    }

                    db.Categories.Add(new Category()
                    {
                        ID = Guid.NewGuid(),
                        CreatedDate = DateTime.Now,
                        ImageID = imageID,
                        IsDeleted = false,
                        Description = model.Description,
                        Name = model.Name,
                        ParentID = model.ParentID,
                        IsHomePage = model.IsHomePage,
                        Position = model.Position,
                        CreatedBy = model.UserID,
                        UpdatedBy = model.UserID,
                        UpdatedDate = DateTime.Now

                    });

                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                throw ex;
            }
        }

        public void Update(CategoryViewModel model)
        {
            try
            {
                using (var db = new THINHTIENDBEntities())
                {
                    var category = (from item in db.Categories
                                    where item.ID == model.ID
                                    select item).FirstOrDefault();

                    if (category != null)
                    {
                        category.UpdatedBy = model.UserID;
                        category.Description = model.Description;
                        category.Name = model.Name;
                        category.IsHomePage = model.IsHomePage;
                        category.Position = model.Position;
                        category.UpdatedDate = DateTime.Now;
                        category.IsDeleted = false;

                        if (model.Photo != null)
                        {
                            var image = (from item in db.Images
                                         where item.ID == category.ImageID
                                         select item).FirstOrDefault();

                            if (image != null)
                            {
                                image.Image1 = model.Photo;
                            }
                            else
                            {
                                Guid imageID = Guid.NewGuid();

                                db.Images.Add(new Image
                                {
                                    ID = imageID,
                                    Size = model.Photo.Length,
                                    Image1 = model.Photo,
                                    Filename = model.Name
                                });

                                category.ImageID = imageID;
                            }
                        }

                        db.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                throw ex;
            }
        }

        public void Delete(List<Guid> ids)
        {
            try
            {
                using (var db = new THINHTIENDBEntities())
                {
                    var categorys = (from item in db.Categories
                                     where ids.Contains(item.ID)
                                     select item).ToList();

                    foreach (var category in categorys)
                    {
                        category.IsDeleted = true;
                    }

                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public CategoryViewModel GetCategoryDetail(Guid categoryID)
        {
            var category = (from item in Database.DbInstant.Categories
                            join image in Database.DbInstant.Images on item.ImageID equals image.ID into left_join
                            where item.ID == categoryID
                            from t in left_join.DefaultIfEmpty()
                            select new CategoryViewModel()
                            {
                                ID = item.ID,
                                Description = item.Description,
                                IsHomePage = item.IsHomePage,
                                Name = item.Name,
                                ParentID = item.ParentID,
                                Position = item.Position,
                                Photo = t.Image1
                            }).FirstOrDefault();

            return category;
        }

        public KeyValuePair<Guid, string>[] GetCategories()
        {
            var results = new List<KeyValuePair<Guid, string>>();
            var categories = (from item in Database.DbInstant.Categories
                              where item.ParentID == null
                              select item).ToList();

            foreach (var item in categories)
            {
                results.Add(new KeyValuePair<Guid, string>(item.ID, item.Name));
            }


            return results.ToArray();
        }

        public KeyValuePair<Guid, string>[] GetCategory()
        {
            var results = new List<KeyValuePair<Guid, string>>();
            var categories = (from item in Database.DbInstant.Categories
                              where item.ParentID != null && item.IsDeleted == false
                              select item).OrderBy(x=>x.Position).ToList().Take(3);

            foreach (var item in categories)
            {
                results.Add(new KeyValuePair<Guid, string>(item.ID, item.Name));
            }


            return results.ToArray();
        }
    }

    public static class CategoryBindingHandler
    {
        public static void GetDataRowCount(GridViewCustomBindingGetDataRowCountArgs e)
        {
            using (var db = new THINHTIENDBEntities())
            {
                e.DataRowCount = (from category in db.Categories
                                  select category).ApplyFilter(e.FilterExpression).Count();
            }
        }

        public static void GetData(GridViewCustomBindingGetDataArgs e)
        {
            using (var db = new THINHTIENDBEntities())
            {
                var query = (from cate in db.Categories
                             join user in db.Users on cate.UpdatedBy equals user.ID
                             select new
                             {
                                 cate.Description,
                                 cate.ID,
                                 cate.ImageID,
                                 cate.IsDeleted,
                                 cate.Name,
                                 cate.IsHomePage,
                                 cate.ParentID,
                                 cate.Position,
                                 cate.UpdatedBy,
                                 cate.UpdatedDate,
                                 cate.CreatedBy,
                                 cate.CreatedDate,
                                 user.UserName
                             }).Distinct().OrderByDescending(p => p.UpdatedDate)
                            .ApplySorting(e.State.SortedColumns)
                            .ApplyFilter(e.State.FilterExpression)
                            .Skip(e.StartDataRowIndex).Take(e.DataRowCount);

                List<CategoryViewModel> data = new List<CategoryViewModel>();
                foreach (dynamic item in query)
                {
                    data.Add(new CategoryViewModel()
                    {
                        ID = item.ID,
                        Description = item.Description,
                        IsHomePage = item.IsHomePage,
                        Name = item.Name,
                        Position = item.Position,
                        ParentID = item.ParentID,
                        UpdatedBy = item.UserName,
                        UpdatedDate = item.UpdatedDate
                    });
                }

                if (data.Count == 0)
                {
                    data.Add(new CategoryViewModel()
                    {
                        ID = Guid.NewGuid()
                    });
                }

                e.Data = data;
            }
        }
    }
}
